﻿using System.Diagnostics;
using System.Threading;
using Android.Content;
using Android.View;
using Java.Lang;
using LeePong.Android.Drawing;
using LeePong.Android.Interaction;
using LeePong.Game;

namespace LeePong
{
    public class GameSurface : SurfaceView, ISurfaceHolder_ICallback, IRunnable
    {
        private bool running;
        private readonly ISurfaceHolder _holder;
        public Engine Engine;
        private GestureDetector _gestureDetector;
        private DrawingManager _drawingManager;

        public GameSurface(Context context, View parentView)
            : base(context)
        {
            _holder = GetHolder();
            _holder.AddCallback(this);
            this.Engine = new Engine();

            _gestureDetector = new GestureDetector(this.Context, new GestureHandler(this));
            _gestureDetector.SetIsLongpressEnabled(false);

            _drawingManager = new DrawingManager(this);
            _drawingManager.ShowFps = true;
           // _drawingManager.DesiredFpsValue = 30;
            //_drawingManager.ShowShadowBalls = true;

            this.Post(() => Init());

            // blurPaint.SetMaskFilter(new BlurMaskFilter(15, BlurMaskFilter.Blur.NORMAL));
            //ballPaint.SetMaskFilter(1, 20, 20, Color.CYAN);

            // parentView.SetBackgroundResource(R.Drawables.LandTexture);
        }

        private void Init()
        {
            Engine.Init(this.Width, this.Height);
            _drawingManager.Init();
        }

        public void SurfaceCreated(ISurfaceHolder iSurfaceHolder)
        {
            var thread = new Thread(this);
            running = true;
            thread.Start();
        }

        public void SurfaceChanged(ISurfaceHolder iSurfaceHolder, int int32, int int321, int int322)
        {
        }

        public void SurfaceDestroyed(ISurfaceHolder iSurfaceHolder)
        {
            running = false;
            this.Engine.IsBusy = false;
        }

        public override bool OnTouchEvent(MotionEvent @event)
        {
            _gestureDetector.OnTouchEvent(@event);
            return true;
        }

        public void Run()
        {
            while (running)
            {
                var canvas = _holder.LockCanvas();
                if (canvas != null)
                {
                    _drawingManager.DoDraw(canvas);
                    _holder.UnlockCanvasAndPost(canvas);
                }
            }
        }
    }
}
